<?php

namespace App\Admin\Controllers;

use App\Admin\Handers\MaterialHander;
use App\Models\AdminUser;
use App\Models\Material;
use App\Models\Purchase;
use App\Models\PurchaseToMaterial;
use App\Models\RecordMaterial;
use App\Models\Store;
use App\Models\Supplier;
use Encore\Admin\Facades\Admin;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\MessageBag;

class PurchaseController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '采购';

    protected $payType = [1 => '现金', 2 => '银行卡', 3 => '微信', 4 => '支付宝', 5 => '赊账'];

    protected $status = [1 => '申请', 2 => '通过', 3 => '拒绝'];

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Purchase());
        
        $grid->column('store', '所属门店')->display(function ($value) {
        	return Arr::get($value, 'detail.name', '本部');
        });
        $grid->column('handler', __('Handler'))
            ->using(AdminUser::All()->pluck('name', 'id')->toArray());
        $grid->column('access_handler', '同意人')
            ->using(AdminUser::where('store_id', 0)->get()->pluck('name', 'id')->toArray());
        $grid->column('total_price', __('Total price'))->display(function($data){
            return $data = '￥'.$data;
        })
        ->sortable();
        $grid->column('other_price', __('Other price'))->display(function($data){
            return $data = '￥'.$data;
        })
        ->sortable();
        $grid->column('price', '实际价格')->display(function($data){
            return $data = '￥'.$data;
        })
        ->sortable();
        $grid->column('pay_type', __('Pay type'))
            ->using($this->payType)->dot([
                1 => 'info', 
                2 => 'success', 
                3 => 'warning', 
                4 => 'danger',
                5 => 'primary'
            ]);
        $grid->column('status')->using([1 => '申请', 2 => '通过', 3 => '拒绝'])
            ->dot([1 => 'info', 2 => 'success', 3 => 'danger']);
        
        $grid->column('created_at', __('Created at'))->sortable();

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
        });
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
			
            $filter->in('store_id', '门店')
	            ->multipleSelect(Store::all()->pluck('name', 'id'));
            
            $filter->equal('handler', __('Handler'))
            ->select(AdminUser::where('store_id', '<=', '0')->pluck('name', 'id'));
            
            $filter->equal('pay_type', __('Pay type'))
                ->radio(Arr::add($this->payType, '', '全部'));
            
            $filter->equal('status', __('Status'))
                ->radio(Arr::add($this->status, '', '全部'));
            
            $filter->between('created_at', '时间')->datetime();
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Purchase::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('number', __('Number'));
        $show->field('description', __('Description'));
        $show->field('handler', __('Handler'));
        $show->field('time', __('Time'));
        $show->field('total_price', __('Total price'));
        $show->field('other_price', __('Other price'));
        $show->field('price', __('Price'));
        $show->field('pay_type', __('Pay type'));
        $show->field('status', __('Status'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('deleted_at', __('Deleted at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $admin = Auth::guard('admin')->user();

        $form = new Form(new Purchase());

        $form->hidden('handler', __('Handler'))->default(Admin::user()->id);

        $form->hasMany('purchasetomaterial', '材料', function (Form\NestedForm $form) {
            $form->select('material_id', '材料')
                ->options(Material::All()->pluck('name', 'id'));
            $form->select('supplier_id', '供应商')
                ->options(Supplier::All()->pluck('company', 'id'));
            $form->number('number', '数量');
            $form->currency('unit_price', '单位价格')->symbol('￥');
        });

        $form->hidden('total_price', __('Total price'));
        $form->hidden('access_handler')->default(0);

        $form->currency('other_price', __('Other price'))
            ->symbol('￥');

        $form->currency('price', '实际支付费用')->symbol('￥');

        $form->textarea('description', __('Description'));

        $form->select('pay_type', '支付方式')
            ->options([1 => '现金', 2 => '银行卡', 3 => '微信', 4 => '支付宝', 5 => '赊账'])
            ->default(1)
            ->rules('required');
	    
        if ($form->isCreating()) {
        	$form->radio('status', __('Status'))
	        ->options([1 => '采购'])
            ->required();
        } else {
        	$form->radio('status', __('Status'))
	        ->options([2 => '通过', 3 => '拒绝'])
            ->required();
        }
        
        
        $form->hidden('number');
        $form->hidden('time');
        
        // 提交前判断是否已经处理过申请
	    $form->submitted(function (Form $form) {
	        if ($form->model()->status > 1) {
	            $error = new MessageBag([
				        'title'   => '提示...',
				        'message' => '已经做过处理了，不要重复处理哦....',
				    ]);
	        	return back()->with(compact('error'));
	        }

	        if (!is_null($form->model()->access_handler)) {
	            $form->input('access_handler', Admin::user()->id);
	        }
	    });
        
        $form->saving(function (Form $form) {
            // 生成编号，采购时间戳
            $form->number = 'CGDD'.time().$form->pay_type.$form->status;
            $form->time = time();

            // 计算合计费用 = 材料单价 * 数量
            $form->total_price = sumMaterialPurchasePrice($form->purchasetomaterial);
            $form->price = $form->total_price + $form->other_price;
            //dd($form->purchasetomaterial);
            // 判断是否为分店采购单 是否为申请没有同意或者拒绝过
	        //dd($form->model());
	        if ($form->model()->store_id > 0 && $form->model()->status == 1) {
	            // 检测总店库存
		        $material_ids = returnMaterialId($form->purchasetomaterial);
		        $needs = returnMaterialNumber($form->purchasetomaterial);
		        $stock = [];
		        //dd($form->purchasetomaterial, $material_ids, $needs);
		        foreach ($material_ids as $k => $v) {
		        	$stock[$v] = PurchaseToMaterial::whereHas('purchase',function (Builder $query) {
			            $query->where('status', 2)->where('store_id', 0);
			        })->where('material_id', $v)
			            ->where('status', 1)
			            ->sum('stock');
		        }
				//dd($material_ids, $stock, $needs);
		        // 检测库存是否充足
		        $res = checkMaterialNum($stock, $needs);
		        
		        if(!$res){
		        	$error = new MessageBag([
				        'title'   => '提示...',
				        'message' => '检测到库存不足....',
				    ]);
				
				    return back()->with(compact('error'));
		        }
		        
		        // 查询采购批次，库存扣减
				$materials = PurchaseToMaterial::whereIn('material_id', $material_ids)
					->whereHas('purchase', function (Builder $query) {
								$query->where('store_id', 0)->where('status', 2);
							})
					->where('stock', '>', 0)
					->where('status', 1)
					->orderBy('material_id')
					->get();
		        // 需求数量按照 material_id 排序
		        foreach ($needs as $k => $v){
					$reduceStock[] = deduction_stock($materials->groupBy('material_id')->toArray()[$k], $v);
				}
		        // 保存到采购中间表
				foreach ($reduceStock as $k => $v)
				{
					foreach ($v as $key => $value) {
						$pToMaterial = PurchaseToMaterial::find($value['id']);
						$pToMaterial->stock = $value['stock'];
						$pToMaterial->sell = $value['sell'];
						$pToMaterial->status = $value['status'];
						//dd($materials->toArray(), $reduceStock, $pToMaterial);
						$res = $pToMaterial->save();
					}
				}
	        }
         
        });

        $form->saved(function (Form $form) {
	            // 找到采购单，生成材料记录表
	            $purchase = Purchase::find($form->model()->id);
	            $param = $purchase->purchasetomaterial;
	            $store_id = empty($form->model()->store_id)?0:$form->model()->store_id;
	            foreach ($param as $k => $v) {
	                $data = [
	                	'store_id' => $store_id,
	                    'purchase_to_material_id' => $v->id,
	                    'material_id' => $v->material_id,
	                    'number' => $v->number,
	                    'description' => $form->description,
	                    'style' => 1, // 新增
	                    'type' => 1 // 采购
	                ];
	                if($store_id == 0) {
	                    $recordMaterial = RecordMaterial::create($data);
	                }
	            }
	            foreach ($form->model()->purchasetomaterial as $k => $v) {
	                $form->model()->purchasetomaterial[$k]['stock'] = $v['number'];
	                $form->model()->purchasetomaterial[$k]['status'] = 1;
	            }
	            //dd($form->model());
	            $form->model()->push();
        });

        // 编辑时不显示提交按钮
        if (Route::currentRouteName() == 'purchases.edit') {
        	$form->disableCreatingCheck();
        	$form->disableEditingCheck();
            $form->footer(function ($footer){
                $footer->disableReset();
            });
        } else {
            $form->footer(function ($footer) {
                $footer->disableEditingCheck();
            });
        }

        return $form;
    }
}
